package com.study.base.io.nio.multireactor;

import com.study.base.io.nio.reactor.Handler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by tan on 2017/7/18.
 */
//TODO  还是不太知道 怎么实现？？ 这只是一个半成品
public class MultiReactor implements Runnable {
	private Selector[] selectors;
	private ServerSocketChannel serverSocket;
	private int next = 0;

	public MultiReactor(int num, int port) throws IOException {
		serverSocket = ServerSocketChannel.open();
		serverSocket.socket().bind(new InetSocketAddress(port));
		serverSocket.configureBlocking(false);

		selectors = new Selector[num];
		Acceptor acceptor = new Acceptor();
		for (int i = 0; i < num; i++) {
			selectors[i] = Selector.open();
			SelectionKey key = serverSocket.register(selectors[i], SelectionKey.OP_ACCEPT);
			key.attach(acceptor);
		}

	}

	@Override
	public void run() {

	}

	class Acceptor implements Runnable {
		@Override
		public synchronized void run() {//注意加上 synchronized
			try {
				SocketChannel socket = serverSocket.accept();
				if (socket != null) {
					new Handler(selectors[next], socket);

					next++;
					if (next == selectors.length) {
						next = 0;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
